package com.tang.qzzp.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * @Author 唐海清
 * @Version V1.0
 * @Description ......
 */
@Component
@Slf4j(topic = "MpHandler")
public class MpHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("MyBatis-Plus : AutoFillInsert");

        Object createTime = this.getFieldValByName("createTime", metaObject);
        Object updateTime = this.getFieldValByName("updateTime", metaObject);
        Object deleted = this.getFieldValByName("deleted", metaObject);
        Object version = this.getFieldValByName("version", metaObject);

        if (createTime != null) {
            this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
        }
        if (updateTime != null) {
            this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
        }
        if (deleted != null) {
            this.strictInsertFill(metaObject, "deleted", Integer.class, 0);
        }
        if (version != null) {
            this.strictInsertFill(metaObject, "version", Integer.class, 1);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("MyBatis-Plus : Update");

        Object updateTime = this.getFieldValByName("updateTime", metaObject);
        Integer version = (Integer) this.getFieldValByName("version", metaObject);

        if (updateTime != null) {
            this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
        }
        if (version != null) {
            this.strictInsertFill(metaObject, "version", Integer.class, version + 1);
        }
    }
}
